from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
from databases import Database
from redis.asyncio import Redis
from sqlalchemy import create_engine
from .config.setting import Settings


@asynccontextmanager
async def lifespan(app:FastAPI):#
    print("正在连接数据库与 Redis...")
    print("✅ 数据库和 Redis 连接成功")
    print("MySQL创建表完成")
    try:
        yield  # ✅ 这是关键，必须要有
    finally:
        print("暂时设置占位")

'''注册路由路径'''
def register_routes(app: FastAPI) -> None:
    from .testapi import testapi_router
    from .LangChain import testapi_router as LangChain
    app.include_router(testapi_router)
    app.include_router(LangChain)

def create_app() -> FastAPI:
    app = FastAPI(
        title=Settings.APP_TITLE,
        description=Settings.APP_DESCRIPTION,
        version=Settings.VERSION,
        lifespan=lifespan,
        openapi_url="/openapi.json",
    )
    # 添加中间件
    app.add_middleware(
        CORSMiddleware,
        allow_origins=Settings.CORS_ORIGINS,
        allow_credentials=False,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    register_routes(app)
    return app